﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Security.Claims;

namespace IdentityService.WebAPI.Controllers.Login;

[Route("[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
    private readonly IIdRepository repository;
    private readonly IdDomainService idService;

    public LoginController(IdDomainService idService, IIdRepository repository)
    {
        this.idService = idService;
        this.repository = repository;
    }

    //[HttpPost]
    //[AllowAnonymous]
    //public async Task<ActionResult> CreateWorld()
    //{
    //    if (await repository.FindByNameAsync("admin") != null)
    //    {
    //        return StatusCode((int)HttpStatusCode.Conflict, "已经初始化过了");
    //    }
    //    User user = new User("admin");
    //    var r = await repository.CreateAsync(user, "XiaTiNode01@");
    //    Debug.Assert(r.Succeeded);
    //    var token = await repository.GenerateChangePhoneNumberTokenAsync(user, "18918999999");
    //    var cr = await repository.ChangePhoneNumAsync(user.Id, "18918999999", token);
    //    Debug.Assert(cr.Succeeded);
    //    r = await repository.AddToRoleAsync(user, "User");
    //    Debug.Assert(r.Succeeded);
    //    r = await repository.AddToRoleAsync(user, "Admin");
    //    Debug.Assert(r.Succeeded);
    //    return Ok();
    //}

    [HttpGet]
    [Authorize]
    public async Task<ActionResult<UserResponse>> GetUserInfo()
    {
        string userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
        List<string> roles = new List<string>();
        foreach (var claim in this.User.FindAll(ClaimTypes.Role).ToList())
        {
            roles.Add(claim.Value);
        }
        var user = await repository.FindByIdAsync(Guid.Parse(userId));
        if (user == null)//可能用户注销了
        {
            return NotFound(new { Data = 404, Msg = "用户未登录" });
        }
        //出于安全考虑，不要机密信息传递到客户端
        //除非确认没问题，否则尽量不要直接把实体类对象返回给前端
        return Ok(new
        {
            Code = 200,
            Data = new UserResponse(user.Id, user.Name, user.Avatar, user.Email, roles, user.PhoneNumber,
                user.CreatedTime),
            Msg = "查询成功"
        });
    }

    [AllowAnonymous]
    [HttpPost]
    public async Task<ActionResult<string>> LoginByUserNameAndPwd(
        LoginByUserNameAndPwdRequest req)
    {
        Console.WriteLine($"UserName: {req.UserName}, Password: {req.Password}");
        (var checkResult, var token) = await idService.LoginByUserNameAndPwdAsync(req.UserName, req.Password);
        if (checkResult.Succeeded) return Ok(new { Code = 200, Data = token, Msg = "登录成功" });
        else if (checkResult.IsLockedOut) //尝试登录次数太多
            return StatusCode((int)HttpStatusCode.Locked, new { Code = (int)HttpStatusCode.Locked, Msg = "用户已经被锁定" });
        else
        {
            string msg = checkResult.ToString();
            return BadRequest(new { Code = 400, Msg = "登录失败" + msg });
        }
    }

    [HttpPut]
    [Authorize]
    [Route("[Action]")]
    public async Task<ActionResult> ChangeMyPassword(ChangeMyPasswordRequest req)
    {
        Guid userId = Guid.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier));
        var resetPwdResult = await repository.ChangePasswordAsync(userId, req.Password);
        if (resetPwdResult.Succeeded)
        {
            return Ok(new { Code = 200, Msg = "更改成功" });
        }
        else
        {
            return BadRequest(new { Code = 400, Msg = resetPwdResult.Errors.SumErrors() });
        }
    }
    
    [HttpPut]
    [Authorize]
    [Route("[Action]")]
    public async Task<ActionResult> ChangeMyInfo(ChangeMyInfoRequest req)
    {
        Guid userId = Guid.Parse(this.User.FindFirstValue(ClaimTypes.NameIdentifier));
        var resetChange = await repository.ChangeInfoAsync(userId, req.Name, req.Avatar);
        return Ok(new { Code = 200, Msg = "更改成功" });
    }
}